angular.module('admin', [
    'ngAnimate',
    'ngMessages',
    'ngResource',
    'ngSanitize',
    'angular-storage',
    'ngFileUpload',
    'ui.keypress',
    'ui.router',

    'angular.patch',
    'ct.ui.router.extras',
    // 'angular-growl',
    'mgcrea.ngStrap',
    "oc.lazyLoad",
    'ui.bootstrap',
    'ui.bootstrap.tpls',
    'ui.bootstrap.pagination',
    'ui.bootstrap.progressbar',

    //'ui.bootstrap.position',
    //'ui.bootstrap.bindHtml',
    //'ui.bootstrap.tooltip',
    'ui.select',
    //'angulartics',
    //'angulartics.piwik',

    'vn.elements',
    //'vn.chart',
    //'vn.rich-editor',

    'templates',
    'session',
    'streams',

    'ng-echarts',
    'ng-datepicker',
    'ngClipboard',

    'users',
    'demo',
    'robot',
    'playPlan',
    'playFile',
    'group',
    'heGroup',
    'robotGroup'


])

    /* Configure ocLazyLoader(refer: https://github.com/ocombe/ocLazyLoad) */
//.config(['$ocLazyLoadProvider', function($ocLazyLoadProvider) {
//    $ocLazyLoadProvider.config({
//        // global configs go here
//    });
//}])

    /* Setup global settings */
    .factory('settings', ['$rootScope', function ($rootScope) {

        // supported languages
        var settings = {
            layout: {
                pageSidebarClosed: false, // sidebar menu state
                pageContentWhite: true, // set page content layout
                pageBodySolid: false, // solid body color state
                pageAutoScrollOnLoad: 1000 // auto scroll to top on page load
            },
            assetsPath: 'assets',
            globalPath: 'assets/global',
            layoutPath: 'assets/',
        };

        $rootScope.settings = settings;
        $rootScope.queryParams = {
            startDate: undefined,
            endDate: undefined,
            version: undefined
        }
        return settings;
    }])

    /* Setup App Main Controller */
//.controller('AppMainController', ['$scope', '$rootScope', function($scope, $rootScope) {
//    //$scope.$on('$viewContentLoaded', function() {
//        //App.initComponents(); // init core components
//        //Layout.init(); //  Init entire layout(header, footer, sidebar, etc) on page load if the partials included in server side instead of loading with ng-include directive
//    //});
//}])

/***
 Layout Partials.
 By default the partials are loaded through AngularJS ng-include directive. In case they loaded in server side(e.g: PHP include function) then below partial
 initialization can be disabled and Layout.init() should be called on page load complete as explained above.
 ***/

    /* Setup Layout Part - Header */
    .controller('HeaderController', ['$scope', function ($scope) {
        $scope.$on('$includeContentLoaded', function () {
            Layout.initHeader(); // init header
        });
    }])

    /* Setup Layout Part - Sidebar */
    .controller('SidebarController', ['$scope', function ($scope) {
        $scope.$on('$includeContentLoaded', function () {
            Layout.initSidebar(); // init sidebar
        });
    }])

    /* Setup Layout Part - Footer */
    .controller('FooterController', ['$scope', function ($scope) {
        $scope.$on('$includeContentLoaded', function () {
            Layout.initFooter(); // init footer
        });
    }])
    .config(['ngClipProvider', function (ngClipProvider) {
        ngClipProvider.setPath("/fonts/ZeroClipboard.swf");
    }])
    .config(function CoreRoute($stateProvider, $urlRouterProvider) {
        $stateProvider.state('admin', {
            abstract: true,
            //params: { user: null },
            templateUrl: 'admin/admin-layout.html',
            controller: 'AdminController as admin',
            resolve: {
                validAdmin: function (store) {
                    return store.get('currentAdmin')
                }
            },

            onEnter: function (validAdmin, $state, store) {

                if (_.isNull(validAdmin)) {
                    $state.go('session.signin')
                }


                return;

            }
        })
            .state('noPage', {
                parent: 'admin',
                url: '/noPage',
                views: {
                    'main': {
                        templateUrl: 'admin/noPage.html'

                    }
                }

            })
        $urlRouterProvider.when('/', '/signin');
        $urlRouterProvider.when('', '/signin');
        $urlRouterProvider.otherwise('/signin');
    })

// 禁用开发时的调试信息输出（TODO: 应放入构建流程自动化处理）
    .config(function DevelopmentDebugging($compileProvider) {
        $compileProvider.debugInfoEnabled(true);
    })

// API 返回代码拦截器
    .config(ApiCodeInterceptorConfiguration)

// ngStrap 配置
    .config(ngStrapConfiguration)

// ui.bootstrap 配置
    .config(uiBootstrapConfiguration)

// ui.select 配置
    .config(uiSelectConfiguration)

// 自定义的 Aside Panel 服务
    .provider('AsidePanel', AsidePanel)
    .config(function AsidePanelConfig($asideProvider, AsidePanelProvider) {
        AsidePanelProvider.defaults = angular.extend(
            $asideProvider.defaults, AsidePanelProvider.defaults
        )
    })

// 自定义的 Confirm Modal 服务
    .provider('ConfirmModal', ConfirmModal)
    .config(function ConfirmModalConfig($modalProvider, ConfirmModalProvider) {
        ConfirmModalProvider.defaults = angular.extend(
            $modalProvider.defaults, ConfirmModalProvider.defaults
        )
    })

// 用来处理 createDate 和 updateDate 的过滤器
    .filter('readable', ReadableFilter)

// 用来获取文件的原始版本
    .filter('replace', ReplaceFilter)

// 用来排序的服务
    .factory('Sorter', SorterService)

// 用来检查用户角色的服务
    .service('RoleChecker', RoleCheckerService)
// 增强angular对input[checkbox]对支持
    .directive(patchCheckboxDirective)

    .constant('Meta', {
        applicationName: document.querySelector('meta[name=application-name]').getAttribute('content'),
        creator: document.querySelector('meta[name=creator]').getAttribute('content'),
        publisher: document.querySelector('meta[name=publisher]').getAttribute('content')
    })

    .constant('API',
    document.querySelector('meta[name=api]').getAttribute('content'))


    .controller('AdminController', AdminController)

    .directive('ngSpinnerBar', ['$rootScope',
        function ($rootScope) {
            return {
                link: function (scope, element, attrs) {
                    // by defult hide the spinner bar
                    element.addClass('hide'); // hide spinner bar by default

                    // display the spinner bar whenever the route changes(the content part started loading)
                    $rootScope.$on('$stateChangeStart', function () {
                        element.removeClass('hide'); // show spinner bar
                    });

                    // hide the spinner bar on rounte change success(after the content loaded)
                    $rootScope.$on('$stateChangeSuccess', function () {
                        element.addClass('hide'); // hide spinner bar
                        $('body').removeClass('page-on-load'); // remove page loading indicator
                        Layout.setSidebarMenuActiveLink('match'); // activate selected link in the sidebar menu

                        // auto scorll to page top
                        //setTimeout(function () {
                        //    App.scrollTop(); // scroll to the top on content load
                        //}, $rootScope.settings.layout.pageAutoScrollOnLoad);
                    });

                    // handle errors
                    $rootScope.$on('$stateNotFound', function () {
                        element.addClass('hide'); // hide spinner bar
                    });

                    // handle errors
                    $rootScope.$on('$stateChangeError', function () {
                        element.addClass('hide'); // hide spinner bar
                    });
                }
            };
        }
    ])

// Handle global LINK click
    .directive('a', function () {
        return {
            restrict: 'E',
            link: function (scope, elem, attrs) {
                if (attrs.ngClick || attrs.href === '' || attrs.href === '#') {
                    elem.on('click', function (e) {
                        e.preventDefault(); // prevent link click for above criteria
                    });
                }
            }
        };
    })

// Handle Dropdown Hover Plugin Integration
    .directive('dropdownMenuHover', function () {
        return {
            link: function (scope, elem) {
                elem.dropdownHover();
            }
        };
    })
    .directive('onFinishRenderFilters', function ($timeout) {
        return {
            restrict: 'AC',
            link: function (scope, element, attr) {
                if (scope.$last === true) {
                    $timeout(function () {
                        Layout.setSidebarMenuActiveLink('match');
                    });
                }
            }
        };
    })
    .filter('percent', function () {
        return function (number) {

            return number + '%';
        }
    })
    .filter('cut',function(){
        return function (value,max) {
            if (!value) return '';

            // max = parseInt(max, 10);
            // if (!max) return value;
            if (value.length <= max) return value;

            value = value.substr(0, max);

            return value + '...';
        };
    })
    .filter('secFilter',function(){
        return function (value) {
            var addZero=function(i){
                if(i>=10){
                    return parseInt(i);
                }
                if(i==0){
                    return '00'
                }
                return '0'+parseInt(i)
            }
            var theTime = parseInt(value);// 秒
            var theTime1 = 0;// 分
            var theTime2 = 0;// 小时
            if(theTime > 60) {
                theTime1 = parseInt(theTime/60);
                theTime = parseInt(theTime%60);
                if(theTime1 > 60) {
                    theTime2 = parseInt(theTime1/60);
                    theTime1 = parseInt(theTime1%60);
                }
            }
            // var result = ""+parseInt(theTime)+"″";
            // if(theTime1 > 0) {
            //     result = ""+parseInt(theTime1)+"′"+result;
            // }
            // if(theTime2 > 0) {
            //     result = ""+parseInt(theTime2)+"°"+result;
            // }
            return addZero(theTime2)+":"+addZero(theTime1)+":"+addZero(theTime);
        }
    })
    .run(["$rootScope", "settings", "$state", function ($rootScope, settings, $state) {
        $rootScope.$state = $state; // state to be accessed from view
        $rootScope.$settings = settings; // state to be accessed from view
    }])